import axios from "axios";
import moment from "moment/moment";
import tradingDates from "./dates";
// import FutuSource  from "./futusource";
import Qmtsource from "./qmtsource";
var futuSource;
var mode = "online"
var source = "FUTU"

function init(callback){
    // futuSource = new FutuSource(callback)
    futuSource = new Qmtsource(callback)
}
function getStartTime(endTime, len){
    if(!len){
        len = 300
    }
    var today = endTime;
    var lenDaysBefore = tradingDates.filter(c=>c<=today).slice(-len)
    return moment.unix(lenDaysBefore[0] / 1000).format("YYYYMMDD093000")
}
function getLatestEndTime(endTime){
    var today = endTime;
    var lenDaysBefore = tradingDates.filter(c=>c<=today).slice(-1)
    return moment.unix(lenDaysBefore[0] / 1000).format("YYYYMMDD150000")
}
async function getKlines(code, period, endTime, lines){
    console.log("getKlines", code, period, endTime, lines)
    var len = lines;
    let p = period
    if(lines.length >0){
        mode = "offline"
    }
    if(period == "2h"){
        p = "1h"
    }
    // if(period == "1M"){
    //     p = "1d"
    //     len = lines * 5
    // }
    let data = []
    if(mode == "online"){
        if(source == "FUTU"){
            data = await futuSource.geKLines(code, p)
        }
    } else {
        // let url = `https://stock.deployment.cn/get_stock_data?code=${code}&period=${p}&end_time=${getLatestEndTime(endTime)}&start_time=${getStartTime(endTime, len)}&count=${len}`
        let url = `https://kesyn-1302292689.cos.ap-beijing.myqcloud.com/his/${code.replace(".SH", "").replace(".SZ", "")}.csv`
        if (!code.includes(".SZ") && !code.includes(".SH")) {
            //外部市场
        }
        const res = await axios.get(url)

        for(var item of res.data.split("\n")){
            if(item){
                let items = item.split(",")
                let kline = {
                    time: moment(items[0], "YYYY/MM/DD").unix() * 1000,
                    open: parseFloat(items[1]),
                    high: parseFloat(items[2]),
                    low: parseFloat(items[3]),
                    close: parseFloat(items[4]),
                    volume: parseFloat(items[5]),
                    amount: parseFloat(items[6])
                }
                data.push(kline)
            }
        }
        data = data.filter(c=>c.time <= endTime).slice(-len)
    }

    if(period == "2h"){

        let newData = []
        var firstK = data[0]
        var hour = moment.unix(firstK.time / 1000).hour()
        var index = 0
        if(hour >12){
            newData.push(firstK)
            index = 1
        }
        //分离数据，两个小时一根蜡烛
        for(let i = index; i < data.length; i+=2){
            let candle = data[i]
            let nextCandle = data[i+1]
            if(!nextCandle){
                newData.push(candle)
                break;
            }
            let newCandle = {
                open: candle.open,
                close: nextCandle.close,
                high: Math.max(candle.high, nextCandle.high),
                low: Math.min(candle.low, nextCandle.low),
                time: nextCandle.time,
                timestamp: nextCandle.time
            }
            newData.push(newCandle)
        }
        data = newData
    }

    // if(period == "1M"){
    //     //group by year and month
    //     let newData = []
    //     let group = {}
    //     for(let k of data){
    //         let time = moment.unix(k.time/1000)
    //         let key = time.format("YYYY-MM")
    //         if(!group[key]){
    //             group[key] = []
    //         }
    //         group[key].push(k)
    //     }
    //     for(let key in group){
    //         let klines = group[key]
    //         let first = klines[0]
    //         let last = klines[klines.length - 1]
    //         let newKline = {
    //             open: first.open,
    //             close: last.close,
    //             high: Math.max(...klines.map(c=>c.high)),
    //             low: Math.min(...klines.map(c=>c.low)),
    //             time: last.time
    //         }
    //         newData.push(newKline)
    //     }
    //     data = newData
    // }


    for(let stock of data) {
        // stock.timestamp = stock.time;
        stock.date = moment.unix(stock.time / 1000).format("YYYY-MM-DD")
    }
    // for(var date of tradingDates){
    //     if(data.filter(c=>c.time == date).length == 0 && date < moment().unix() * 1000){
    //         console.log("missing", moment.unix(date / 1000).format("YYYY-MM-DD"))
    //     }
    // }
    // console.log(data)
    return data;
}

export default {getKlines, init}
